//
//  MDXPGApplianceApi.m
//  MideaWorld_Zizhu
//
//  Created by Minus on 4/23/15.
//  Copyright (c) 2015 Minus. All rights reserved.
//

#import "MDXPGApplianceApi.h"
#import "MDNetworkUtils.h"
#import "MDSecurityHandler.h"
#import "MDMessageManagerHandler.h"
#import "MDSharePerferenceHandler.h"
#import "MDDateTansformer.h"
#import "MDUserDefaults.h"

#import "JsonParser.h"
#import "FormGenerator.h"
#import "FactoryDataBody.h"
#import "IDataBodyDevStauts.h"
#import "DateUtil.h"
#import "AirConditionerFuncSN.h"
#import "IDataBodyDeHumiStatus.h"
#import "IDataBodyHumiStatus.h"

#import <org/json/JSONObject.h>
#import <java/lang/Boolean.h>
#import <java/lang/Integer.h>
#import <java/util/ArrayList.h>
#import <java/util/List.h>
#import <java/util/HashMap.h>
#import <java/util/Map.h>

#define CLIENTTYPE_IOS @"2"


#pragma mark - C++ functions

/**
 *  剪切图片
 *
 *  @param image 图片
 *
 *  @return 剪切后的图片
 */
UIImage *clipImageToSquare(UIImage *image)
{
    CGSize size = image.size;
    
    if (size.width == size.height)
    {
        return image;
    }
    
    CGFloat width = size.width > size.height ? size.height : size.width;
    
    CGRect rect = CGRectMake((size.width-width)/2.0, (size.height-width)/2.0, width, width);
    
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    
    UIImage *resultImage = [UIImage imageWithCGImage:imageRef];
    
    CGImageRelease(imageRef);
    
    return resultImage;
}


/**
 *  空调机型识别
 *
 *  @param d1    d1
 *  @param d2    d2
 *  @param data  data
 *  @param mfunc 空调机型识别结果
 */
void setFuncEnable(jbyte d1, jbyte d2, IOSByteArray *data, AirConditionerFuncs *mfunc)
{
    NSLog(@"data = %p %d", data, [data byteAtIndex:0]);
    if (d1 == 0x02)
    {
        switch (d2)
        {
            case 0x12:  // ECO
                mfunc->eco_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                mfunc->special_eco_ = [data byteAtIndex:0] == 0x02 ? YES : NO;
                break;
                
            case 0x13:  // 8度制热
                mfunc->eightHot_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            case 0x14:  // 冷暖机
            {
                mfunc->hotcold_ = [data byteAtIndex:0];
                if (mfunc->hotcold_ == AirConditionerFuncs_get_COLDHOT_AC())
                {
                    mfunc->cool_ = YES;
                    mfunc->hot_ = YES;
                    mfunc->dry_ = YES;
                    mfunc->auto__ = YES;
                }
                else if (mfunc->hotcold_ == AirConditionerFuncs_get_HOT_AC())
                {
                    mfunc->cool_ = NO;
                    mfunc->dry_ = NO;
                    mfunc->hot_ = YES;
                    mfunc->auto__ = YES;
                }
                else if (mfunc->hotcold_ == AirConditionerFuncs_get_COLD_AC_SUB())
                {
                    mfunc->cool_ = YES;
                    mfunc->dry_ = NO;
                    mfunc->hot_ = NO;
                    mfunc->auto__ = NO;
                }
                else    // 默认单冷
                {
                    mfunc->hot_ = NO;
                    mfunc->cool_ = YES;
                    mfunc->dry_ = YES;
                    mfunc->auto__ = YES;
                }
            }
                break;
                
            case 0x15:  // 左右风
            {
                // 0：无垂直导风条，有水平导风条
                // 1：有垂直导风条，有水平导风条
                // 2：无垂直导风条，无水平导风条
                // 3：有垂直导风条，无水平导风条
                // 水平垂直导风条,没有B5上报的时候，默认为0：无垂直导风条，有水平导风条
                switch ([data byteAtIndex:0])
                {
                    case 0x00:
                        mfunc->leftrightFan_ = NO;
                        mfunc->updownFan_ = YES;
                        break;
                        
                    case 0x01:
                        mfunc->leftrightFan_ = YES;
                        mfunc->updownFan_ = YES;
                        break;
                        
                    case 0x02:
                        mfunc->leftrightFan_ = NO;
                        mfunc->updownFan_ = NO;
                        break;
                        
                    case 0x03:
                        mfunc->leftrightFan_ = YES;
                        mfunc->updownFan_ = NO;
                        break;
                        
                    default:
                        break;
                }
            }
//                mfunc->leftrightFan_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            case 0x16:  // 电量检测
//                mfunc->powerCal_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                mfunc->powerCal_ = NO;
                break;
                
            case 0x17:  // 堵脏
            {
                // 0:无过滤网清洗提示，无滤网更换提示
                // 1:有过滤网清洗提示，有滤网更换提示
                // 2：有过滤网清洗提示，无滤网更换提示
                // 3：无过滤网清洗提示，有滤网更换提示
                switch ([data byteAtIndex:0])
                {
                    case 0x00:
                        mfunc->nestCheck_ = NO;
                        mfunc->nestNeedChange_ = NO;
                        break;
                        
                    case 0x01:
                        mfunc->nestCheck_ = YES;
                        mfunc->nestNeedChange_ = YES;
                        break;
                        
                    case 0x02:
                        mfunc->nestCheck_ = YES;
                        mfunc->nestNeedChange_ = NO;
                        break;
                        
                    case 0x03:
                        mfunc->nestCheck_ = NO;
                        mfunc->nestNeedChange_ = YES;
                        break;
                        
                    default:
                        break;
                }
            }
                break;
                
            case 0x19:  // 电辅热
                mfunc->dianfure_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            case 0x1a:  // 制热强劲风
            {
                // 0:无制热强劲风,有制冷强劲风
                // 1：有制热强劲风，有制冷强劲风
                // 2：无制热强劲风，无制冷强劲风
                // 3：有制热强劲风，无制冷强劲风
                switch ([data byteAtIndex:0])
                {
                    case 0x00:
                        mfunc->strongHot_ = NO;
                        mfunc->strongCool_ = YES;
                        break;
                        
                    case 0x01:
                        mfunc->strongHot_ = YES;
                        mfunc->strongCool_ = YES;
                        break;
                        
                    case 0x02:
                        mfunc->strongHot_ = NO;
                        mfunc->strongCool_ = NO;
                        break;
                        
                    case 0x03:
                        mfunc->strongHot_ = YES;
                        mfunc->strongCool_ = NO;
                        break;
                        
                    default:
                        break;
                }
            }
                break;
                
            case 0x22:
                mfunc->unitChangeable_ = [data byteAtIndex:0] == 0x00 ? YES : NO;
                break;
                
            default:
                break;
        }
    }
}

/**
 *  除湿机型识别
 *
 *  @param d1
 *  @param d2
 *  @param data
 *  @param mfunc 除湿机型识别结果
 */
void setFuncEnable(jbyte d1, jbyte d2, IOSByteArray *data, DeHumiFunctions *mfunc)
{
    if (d1 == 0x02)
    {
        switch (d2)
        {
            case 0x10:  // 风机类型
                mfunc->MotorType_ = [data byteAtIndex:0];
                break;
                
            case 0x1d:  // 水泵
                mfunc->Pumb_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            case 0x1e:  // 负离子
                mfunc->Anion_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            case 0x1f:  // 自动除湿
                mfunc->AutoDehumi_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            case 0x20:  // 左右风
                mfunc->DryClothes_ = [data byteAtIndex:0] == 0x01 ? YES : NO;
                break;
                
            default:
                break;
        }
    }
}

/**
 *  加湿机型识别
 *
 *  @param d1
 *  @param d2
 *  @param data
 *  @param mfunc 加湿机型识别结果
 */
void setFuncEnable(jbyte d1, jbyte d2, IOSByteArray *data, HumiFunctions *mfunc)
{
    void (^setTo)(boolean_t, ...) = ^(boolean_t t, ...) {
        
        va_list arg_ptr;
        
        va_start(arg_ptr, t);
        
        boolean_t *value;
        
        while ((value = va_arg(arg_ptr, boolean_t *)))
        {
            *value = t;
        }
        
        va_end(arg_ptr);
    };
    
    if (d1 == 0x02)
    {
        switch (d2)
        {
            case 0x10:  // 风机类型
                mfunc->MotorType_ = [data byteAtIndex:0];
                break;
                
            case 0x23:  // 加湿类型
            {
                mfunc->humi_ = [data byteAtIndex:0];
                
                switch ([data byteAtIndex:0])
                {
                    case 0:
                        setTo(NO, &mfunc->High_, &mfunc->Middle_, &mfunc->Low_, &mfunc->Strong_, &mfunc->Auto_, &mfunc->NoPolar_, nullptr);
                        break;
                        
                    case 1:
                        setTo(NO, &mfunc->High_, &mfunc->Low_, &mfunc->Strong_, &mfunc->Auto_, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->Middle_, nullptr);
                        break;
                        
                    case 2:
                        setTo(NO, &mfunc->Middle_, &mfunc->Strong_, &mfunc->Auto_, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->High_, &mfunc->Low_, nullptr);
                        break;
                        
                    case 3:
                        setTo(NO, &mfunc->Strong_, &mfunc->Auto_, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->High_, &mfunc->Middle_, &mfunc->Low_, nullptr);
                        break;
                        
                    case 4:
                        setTo(NO, &mfunc->Auto_, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->High_, &mfunc->Middle_, &mfunc->Low_, &mfunc->Strong_, nullptr);
                        break;
                        
                    case 5:
                        setTo(NO, &mfunc->Middle_, &mfunc->Strong_, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->High_, &mfunc->Low_, &mfunc->Auto_, nullptr);
                        break;
                        
                    case 6:
                        setTo(NO, &mfunc->Strong_, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->High_, &mfunc->Low_, &mfunc->Auto_, &mfunc->Middle_, nullptr);
                        break;
                        
                    case 7:
                        setTo(NO, &mfunc->NoPolar_, nullptr);
                        setTo(YES, &mfunc->High_, &mfunc->Low_, &mfunc->Auto_, &mfunc->Middle_, &mfunc->Strong_, nullptr);
                        break;
                        
                    case (jbyte)0xff:
                        setTo(NO, &mfunc->High_, &mfunc->Middle_, &mfunc->Low_, &mfunc->Strong_, &mfunc->Auto_, nullptr);
                        setTo(YES, &mfunc->NoPolar_, nullptr);
                        break;
                        
                    default:
                        break;
                }
            }
                break;
                
            case 0x24:  // 灯光
                mfunc->light_ = [data byteAtIndex:0];
                break;
                
            default:
                break;
        }
    }
}

/**
 *  美的协议解密，将reply解密后转换为IOSByteArray，然后截取一部分内容
 *  截取的内容不包含协议版本号
 */
IOSByteArray *replyToByteArray(NSString *reply, NSString *accessToken)
{
    // 调用美的SDK解密
    reply = [MideaDataSecurity sensitiveDataDecryption:accessToken reply:reply];
    
    // 将字符串数字，转换为int
    NSArray *numbers = [reply componentsSeparatedByString:@","];
    
    char bytes[1024];
    for (int i = 0; i < [numbers count]; i++)
    {
        NSString *number = numbers[i];
        bytes[i] = (char)[number intValue];
    }
    
    // 获取解密后的数据
    NSData *data = [[NSData alloc] initWithBytes:bytes length:[numbers count]];
    MideaProtocol *protocol = [[MideaProtocol alloc] initWithNSData:data];
    
    // 去掉前面10个字节的数据
    int count = 0;
    
    if ([protocol.messageArray count] > (10 + 1))
    {
        count = (int)[protocol.messageArray count] - 10 - 1;
    }
    
    IOSByteArray *byteArray = [IOSByteArray arrayWithLength:count];
    
    for (int i = 0; i < count; i++)
    {
        *[byteArray byteRefAtIndex:i] = (char)[protocol.messageArray[i+10] intValue];
    }
    
    return byteArray;
}

/**
 *  美的协议解密，将reply解密后转换为IOSByteArray
 */
IOSByteArray *replyToTotalByteArray(NSString *reply, NSString *accessToken)
{
    reply = [MideaDataSecurity sensitiveDataDecryption:accessToken reply:reply];
    
    NSArray *numbers = [reply componentsSeparatedByString:@","];
    
    char bytes[1024];
    for (int i = 0; i < [numbers count]; i++)
    {
        NSString *number = numbers[i];
        bytes[i] = (char)[number intValue];
    }
    
    NSData *data = [[NSData alloc] initWithBytes:bytes length:[numbers count]];
    MideaProtocol *protocol = [[MideaProtocol alloc] initWithNSData:data];
    
    IOSByteArray *byteArray = [IOSByteArray arrayWithLength:[protocol.messageArray count]];
    
    for (int i = 0; i < [protocol.messageArray count]; i++)
    {
        *[byteArray byteRefAtIndex:i] = (char)[protocol.messageArray[i] intValue];
    }
    
    return byteArray;
}



#pragma mark - MDXPGApplianceApi
////////////////////////////////////////////////////////////////
///     网络请求类
////////////////////////////////////////////////////////////////

static const BOOL isFunc = YES;


@interface MDXPGApplianceApi ()
{
    MDNetworkUtils *_netUtil;
    
    FormGenerator *_formGenerator;
    JsonParser *_jsonParser;
    
    NSString *_loginID;
    User *_currentUser;
    NSString *_currentFamilyID;
    
    MDSharePerferenceHandler *_sharePerferenceHandler;  // B5机型识别结果本地缓存
    
    BOOL B5Timeout;     // B5机型识别 是否超时 标识
    
    NSString *_currentQRCodeSN;
}

@property (nonatomic, strong) DeviceStatus *status; // 空调状态保存，用于透传命令失败后状态恢复
@property (nonatomic, strong) DeHumidification *dehumidifier_status;    // 除湿状态保存，用于透传命令失败后状态恢复
@property (nonatomic, strong) Humidification *humidifier_status;        // 加湿状态保存，用于透传命令失败后状态恢复

@end

@implementation MDXPGApplianceApi

@synthesize status = _status;
@synthesize dehumidifier_status = _dehumidifier_status;
@synthesize humidifier_status = _humidifier_status;

+ (instancetype)getInstance
{
    static MDXPGApplianceApi *sharedInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

+ (MDDeviceManager *)deviceManager
{
    static MDDeviceManager *_deviceManager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _deviceManager = [[MDDeviceManager alloc] initWithAppId:BaseAPI_get_appId_()
                                                         appKey:BaseAPI_get_appKey_()
                                                            src:BaseAPI_get_src_()
                                                      isRelease:YES];
    });
    
    return _deviceManager;
}

- (instancetype)init
{
    self = [super init];
    
    if (self)
    {
        _netUtil = [MDNetworkUtils getInstance];
        
        _formGenerator = [FormGenerator getInstanceWithSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:CLIENTTYPE_IOS];
        _jsonParser = [JsonParser getInstance];
        
        _sharePerferenceHandler = [[MDSharePerferenceHandler alloc] init];
        
        _elecTotalDay = 30;
        
        B5Timeout = NO;
    }
    
    return self;
}

#pragma mark - Private

- (NSString *)getTargetURLAppendParams:(int)key
{
    return [self getTargetURLAppendParams:key isFunc:NO];
}

- (NSString *)getTargetURLAppendParams:(int)key isFunc:(BOOL)isFunc
{
    NSString *mapString;
    
    if (isFunc)
    {
        mapString = [BaseAPI_map_ getWithId:JavaLangInteger_valueOfWithInt_(BaseAPI_get_APP2BASE())];
        mapString = [mapString stringByAppendingString:@"?serviceUrl="];
        mapString = [mapString stringByAppendingString:[BaseAPI_map_ getWithId:JavaLangInteger_valueOfWithInt_(key)]];
    }
    else
    {
        mapString = [BaseAPI_map_ getWithId:JavaLangInteger_valueOfWithInt_(key)];
    }
    
    if ([mapString hasPrefix:@"/"])
    {
        mapString = [mapString substringFromIndex:1];
    }
    
    return mapString;
}

- (NSString *)JSONStringFromForm:(NSString *)form
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[self JSONObjectFromForm:form]
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:NULL];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return jsonString;
}

- (NSDictionary *)JSONObjectFromForm:(NSString *)form
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSArray *array = [form componentsSeparatedByString:@"&"];
    
    for (NSString *string in array)
    {
        if ([string length] > 0 && [string rangeOfString:@"="].location != NSNotFound)
        {
            NSArray *tempArray = [string componentsSeparatedByString:@"="];
            [params setObject:tempArray[1] forKey:tempArray[0]];
        }
    }
    
    return params;
}

- (NSDate *)toUTCTime:(NSString *)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    
    NSDate *date = [formatter dateFromString:time];
    
    return date;
}

#pragma mark - Setters and Getters

- (void)setStatus:(DeviceStatus *)status
{
    _status = [[DeviceStatus alloc] initWithDeviceStatus:status];
}

- (DeviceStatus *)status
{
    if (!_status)
    {
        _status = [[DeviceStatus alloc] init];
        _status->setTemperature_ = 26;
        _status->powerStatus_ = IDataBody_get_ON();
        _status->fanSpeed_ = IDataBodyDevStauts_get_WIND_SPEED_AUTO();
        _status->mode_ = IDataBodyDevStauts_get_MODE_COLD();
    }
    
    return [[DeviceStatus alloc] initWithDeviceStatus:_status];
}

- (void)setDehumidifier_status:(DeHumidification *)dehumidifier_status
{
    _dehumidifier_status = [[DeHumidification alloc] initWithDeHumidification:dehumidifier_status];;
}

- (DeHumidification *)dehumidifier_status
{
    if (!_dehumidifier_status)
    {
        _dehumidifier_status = [DeHumidification new];
        _dehumidifier_status->powerMode_ = 0;
        _dehumidifier_status->windSpeed_ = 80;
        _dehumidifier_status->humidity_set_ = 50;
        _dehumidifier_status->powerMode_ = 1;
        _dehumidifier_status->windSpeed_ = IDataBodyDeHumiStatus_get_WIND_SPEED_LOW();
    }
    
    return _dehumidifier_status;
}

- (void)setHumidifier_status:(Humidification *)humidifier_status
{
    _humidifier_status = [[Humidification alloc] initWithHumidification:humidifier_status];
}

- (Humidification *)humidifier_status
{
    if (!_humidifier_status)
    {
        _humidifier_status = [Humidification new];
        _humidifier_status->powerMode_ = 0;
        _humidifier_status->windSpeed_ = 80;
        _humidifier_status->humidity_set_ = 50;
        _humidifier_status->powerMode_ = 1;
        _humidifier_status->windSpeed_ = IDataBodyHumiStatus_get_WIND_SPEED_AUTO();
        _humidifier_status->humidity_ = 0;
    }
    
    return _humidifier_status;
}

#pragma mark - 二维码

/**
 *  @brief  检查二维码是否合法
 */
- (BOOL)isQRCodeValid:(NSString *)qrcode
{
    return [[MDXPGApplianceApi deviceManager] isQRCodeValid:qrcode];
}

/**
 *  @brief  从二维码获取目标设备SSID
 */
- (NSString *)getSSIDfromQRCode:(NSString *)qrcode
{
    return [[MDXPGApplianceApi deviceManager] getSSIDfromQRCode:qrcode];
}

/**
 *  @brief  从二维码获取目标设备SN
 */
- (NSString *)getSNfromQRCode:(NSString *)qrcode
{
    _currentQRCodeSN = [[MDXPGApplianceApi deviceManager] getSNfromQRCode:qrcode];
    
    return _currentQRCodeSN;
}

/**
 *  @brief  获取用户当前连接的SSID
 */
- (NSString *)getCurrentSSID
{
    return [[MDXPGApplianceApi deviceManager] getCurrentSSID];
}

/**
 *  @brief  wifi密码长度是否合法
 */
- (BOOL)isValidWifiPassword:(NSString *)password security:(MDWifiSecurity)security
{
    return [[MDXPGApplianceApi deviceManager] isValidWifiPassword:password security:security];
}


#pragma mark - 用户

/**
 * 检测邮箱可用
 */
- (void)checkEmailAvailability:(NSString *)email completion:(void (^)(BaseMessage *, int))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CHECK_EMAIL()];
    
    NSString *form = [_formGenerator CheckEmailAvailableRequestWithNSString:email
                                                                    withInt:BaseAPI_get_CHECK_EMAIL()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        int status = -1;
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0) // 成功
            {
                status = [_jsonParser CheckEmailAvailableResponseWithNSString:responseString];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, status);
        }
    }];
}

/**
 * 用户注册
 */
- (void)userRegister:(NSString *)userName password:(NSString *)password completion:(void (^)(BaseMessage *))completion
{
    NSString *form = [_formGenerator UserRegisterRequestWithNSString:userName
                                                        withNSString:password
                                                             withInt:BaseAPI_get_USER_REGISTER()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_REGISTER()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

/**
 * 获取登陆ID
 */
- (void)getLoginID:(NSString *)email completion:(void (^)(BaseMessage *, NSString *))completion
{
    NSString *form = [_formGenerator getLoginIDRequestWithNSString:email withInt:BaseAPI_get_USER_ID()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_ID()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        NSString *loginID = nil;
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0) // 成功
            {
                loginID = [_jsonParser getLoginIdResponseWithNSString:responseString];
                _loginID = loginID;
            }
        }
        
        if (completion)
        {
            completion(baseMessage, loginID);
        }
    }];
}

/**
 * 用户登录
 */
- (void)userLogin:(NSString *)email password:(NSString *)password loginID:(NSString *)loginID completion:(void (^)(BaseMessage *, User *))completion
{
    NSString *deviceToken = [MDUserDefaults sharedInstance].pushNotificationToken ? : nil;
    
    NSString *form = [_formGenerator userLoginRequestWithNSString:email withNSString:password withNSString:loginID withInt:BaseAPI_get_USER_EMAIL_LOGIN() withNSString:deviceToken];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_EMAIL_LOGIN()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        User *user = nil;
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0) // 成功
            {
                user = [_jsonParser userLoginResponseWithNSString:responseString];
                _currentUser = user;
            }
        }
        
        if (completion)
        {
            completion(baseMessage, user);
        }
    }];
}

/**
 * 用户注销
 */
- (void)userLogout:(NSString *)sessionID completion:(void (^)(BaseMessage *))completion
{
    NSString *form = [_formGenerator userLogoutRequestWithNSString:sessionID withInt:BaseAPI_get_USER_LOGOUT()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_LOGOUT()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                _currentUser = nil;
                _loginID = nil;
                _currentFamilyID = nil;
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)userLogout:(void (^)(BaseMessage *))completion
{
    [self userLogout:[_currentUser getSessionId] completion:completion];
}

/**
 * 获取用户信息
 */
- (void)getUserInfo:(NSString *)sessionID completion:(void (^)(BaseMessage *, UserInfo *))completion
{
    NSString *form = [_formGenerator getUserInfoRequestWithNSString:sessionID withInt:BaseAPI_get_USER_INFO()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_INFO()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        UserInfo *userInfo = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                userInfo = [_jsonParser getUserInfoResponseWithNSString:responseString];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, userInfo);
        }
    }];
}

- (void)getUserInfo:(void (^)(BaseMessage *, UserInfo *))completion
{
    [self getUserInfo:[_currentUser getSessionId] completion:completion];
}

/**
 * 用户修改密码
 */
- (void)updatePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword sessionID:(NSString *)sessionID accessToken:(NSString *)accessToken completion:(void (^)(BaseMessage *))completion
{
    NSString *form = [_formGenerator modufyPasswordWithNSString:sessionID withNSString:accessToken withNSString:oldPassword withNSString:newPassword withInt:BaseAPI_get_USER_UPDATE_PASSWORD()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_UPDATE_PASSWORD()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)updatePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword completion:(void (^)(BaseMessage *))completion
{
    [self updatePassword:oldPassword newPassword:newPassword sessionID:[_currentUser getSessionId] accessToken:[_currentUser getAccessToken] completion:completion];
}

/**
 * 用户忘记密码，用邮箱重新设置
 */
- (void)forgetPassword:(NSString *)email completion:(void (^)(BaseMessage *))completion
{
    NSString *form = [_formGenerator resetPasswordWithNSString:email withInt:BaseAPI_get_USER_RESET_PASSWORD()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_RESET_PASSWORD()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

/**
 *  @brief  修改用户信息
 */
- (void)userModifyInfo:(NSString *)nickName completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_MODIFY()];
    
    NSString *form = [_formGenerator userModifyInfoWithNSString:[_currentUser getSessionId] withNSString:nickName withInt:BaseAPI_get_USER_MODIFY()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

#pragma mark - 家庭

/**
 * 获取家庭列表
 */
- (void)getHomeList:(NSString *)sessionID completion:(void (^)(BaseMessage *, NSArray *))completion
{
    NSString *form = [_formGenerator getHomeListRequestWithNSString:sessionID withInt:BaseAPI_get_HOME_LIST()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_HOME_LIST()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSMutableArray *familyInfos = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                id<JavaUtilList> familyList = [_jsonParser getHomeListResponseWithNSString:responseString];
                
                familyInfos = [NSMutableArray new];
                
                for (id object in familyList)
                {
                    [familyInfos addObject:object];
                }
                
                // 保存家庭ID
                if ([familyInfos count] > 0)
                {
                    FamilyInfo *info = [familyInfos firstObject];
                    _currentFamilyID = [info getId];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, familyInfos);
        }
    }];
}

- (void)getHomeList:(void (^)(BaseMessage *, NSArray *))completion
{
    [self getHomeList:[_currentUser getSessionId] completion:completion];
}

/**
 * 新建家庭
 */
- (void)createFamily:(NSString *)sessionID name:(NSString *)name description:(NSString *)description address:(NSString *)address completion:(void (^)(BaseMessage *, Family *))completion
{
    NSString *form = [_formGenerator createFamilyRequestWithNSString:sessionID withNSString:name withNSString:description withNSString:address withInt:BaseAPI_get_HOME_ADD()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_HOME_ADD()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        Family *family = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                family = [_jsonParser createFamilyResponseWithNSString:responseString];
                
                // 保存家庭ID
                if (family)
                {
                    _currentFamilyID = [family getId];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, family);
        }
    }];
}

- (void)createFamily:(NSString *)name description:(NSString *)description address:(NSString *)address completion:(void (^)(BaseMessage *, Family *))completion
{
    [self createFamily:[_currentUser getSessionId] name:name description:description address:address completion:completion];
}


#pragma mark - 设备

/**
 * 获取家庭设备列表
 */
- (void)getDeviceList:(NSString *)sessionID homeGroupID:(NSString *)homeGroupID completion:(void (^)(BaseMessage *, NSArray *))completion
{
    NSString *form = [_formGenerator getApplianceListRequestWithNSString:sessionID withNSString:homeGroupID withInt:BaseAPI_get_DEVICE_LIST()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_DEVICE_LIST()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSMutableArray *applianceInfos = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                id<JavaUtilList> deviceList = [_jsonParser getApplianceListResponseWithSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:responseString withNSString:[_currentUser getAccessToken]];
                
                applianceInfos = [NSMutableArray new];
                
                for (id object in deviceList)
                {
                    [applianceInfos addObject:object];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, applianceInfos);
        }
    }];
}

- (void)getDeviceList:(void (^)(BaseMessage *, NSArray *))completion
{
    [self getDeviceList:[_currentUser getSessionId] homeGroupID:_currentFamilyID completion:completion];
}


/**
 * 家电透传
 */
- (void)transparentCmd:(NSString *)sessionID accessToken:(NSString *)accessToken applianceID:(NSString *)applianceID funcID:(NSString *)funcID order:(IOSByteArray *)order completion:(void (^)(BaseMessage *, NSString *, DeviceStatus *))completion
{
    NSString *form = [_formGenerator applianceSendRequestWithNSString:sessionID
                                                         withNSString:accessToken
                                                         withNSString:applianceID
                                                         withNSString:funcID
                                                        withByteArray:order
                                                              withInt:BaseAPI_get_DEVICE_CMD()
                                            withMessageManagerHandler:[MDMessageManagerHandler new]];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_DEVICE_CMD()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSString *reply = nil;
        DeviceStatus *status = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
            
            status = self.status;
            
            if (status == nil)
            {
                status = self.status;
                status->setTemperature_ = 26;
                status->fanSpeed_ = IDataBodyDevStauts_get_WIND_SPEED_AUTO();
                status->mode_ = IDataBodyDevStauts_get_MODE_AUTO();
                status->eco_ = IDataBody_get_OFF();
                status->Eight_Hot_ = IDataBody_get_OFF();
                status->leftRightFan_ = IDataBody_get_OFF();
                status->updownFan_ = IDataBody_get_OFF();
                status->powerStatus_ = IDataBody_get_OFF();
                status->tempUnit_ = IDataBodyDevStauts_get_TEMPERATURE_Celsius();
                self.status = status;
            }
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
                reply = (NSString *)[info getBeanInfo];
                
                IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
                
                status = (DeviceStatus *)[[FactoryDataBody createFactoryDataBodyResponse] toObjectWithByteArray:byteArray];
                
                IOSByteArray *totalByteArray = replyToTotalByteArray(reply, [_currentUser getAccessToken]);
                status->protocol_ = [totalByteArray byteAtIndex:8];
                
                self.status = status;
                
                [FactoryDataBody setProtocolWithByte:status->protocol_];
            }
            else
            {
                status = self.status;
            }
        }
        
        if (completion)
        {
            completion(baseMessage, reply, status);
        }
    }];
}

- (void)transparentCmd:(NSString *)applianceID order:(IOSByteArray *)order completion:(void (^)(BaseMessage *, NSString *, DeviceStatus *))completion
{
    [self transparentCmd:[_currentUser getSessionId] accessToken:[_currentUser getAccessToken] applianceID:applianceID funcID:@"1000" order:order completion:completion];
}

- (void)transparentCmd:(NSString *)applianceID order:(IOSByteArray *)order completionForDehumidifier:(void (^)(BaseMessage *, NSString *, DeHumidification *))completion
{
    [self transparentCmd:applianceID order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
        
        BaseMessage *baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        NSString *reply = nil;
        DeHumidification *status;
        
        if ([baseMessage getCode] == 0)
        {
            MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
            reply = (NSString *)[info getBeanInfo];
            
            IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
            
            FactoryDataBody *data = (FactoryDataBody *)[FactoryDataBody cmdResponseWithInt:FactoryDataBody_get_Dehumidifier()];
            status = (DeHumidification *)[data toObjectWithByteArray:byteArray];
            self.dehumidifier_status = status;
            
            completion(baseMessage, reply, status);
        }
        else
        {
            reply = @"";
            
            status = self.dehumidifier_status;
            
            completion(baseMessage, reply, status);
        }
    }];
}

- (void)transparentCmd:(NSString *)applianceID order:(IOSByteArray *)order completionForHumidifier:(void (^)(BaseMessage *, NSString *, Humidification *))completion
{
    [self transparentCmd:applianceID order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
        
        BaseMessage *baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        NSString *reply = nil;
        Humidification *status;
        
        if ([baseMessage getCode] == 0)
        {
            MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
            reply = (NSString *)[info getBeanInfo];
            
            IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
            
            FactoryDataBody *data = (FactoryDataBody *)[FactoryDataBody cmdResponseWithInt:FactoryDataBody_get_Humidifier()];
            status = (Humidification *)[data toObjectWithByteArray:byteArray];
            self.humidifier_status = status;
            
            completion(baseMessage, reply, status);
        }
        else
        {
            reply = @"";
            
            status = self.humidifier_status;
            
            completion(baseMessage, reply, status);
        }
    }];
}

/**
 *  @brief  不处理 JSON 数据
 */
- (void)transparentCmd:(NSString *)applianceID order:(IOSByteArray *)order completionWithoutHandling:(void (^)(NSError *error, NSString *responseString))completion
{
    NSString *sessionID = [_currentUser getSessionId];
    NSString *accessToken = [_currentUser getAccessToken];
    NSString *funcID = @"1000";
    
    NSString *form = [_formGenerator applianceSendRequestWithNSString:sessionID
                                                         withNSString:accessToken
                                                         withNSString:applianceID
                                                         withNSString:funcID
                                                        withByteArray:order
                                                              withInt:BaseAPI_get_DEVICE_CMD()
                                            withMessageManagerHandler:[MDMessageManagerHandler new]];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_DEVICE_CMD()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        if (completion)
        {
            completion(error, responseString);
        }
    }];
}

/**
 * 删除家电
 */
- (void)deleteDevice:(NSString *)sessionID applianceID:(NSString *)applianceID completion:(void (^)(BaseMessage *))completion
{
    NSString *form = [_formGenerator deleteAppianceRequestWithNSString:sessionID
                                                          withNSString:applianceID
                                                               withInt:BaseAPI_get_DEVICE_DELETE()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_DEVICE_DELETE()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)deleteDevice:(NSString *)applianceID completion:(void (^)(BaseMessage *))completion
{
    [self deleteDevice:[_currentUser getSessionId] applianceID:applianceID completion:completion];
}

/**
 *  获取家电信息
 */
- (void)getDeviceInfo:(NSString *)userID familyID:(NSString*)familyID applianceID:(NSString *)applianceID completion:(void(^)(BaseMessage *baseMessage))completion
{
    
}

- (void)getDeviceInfo:(NSString *)applianceID completion:(void (^)(BaseMessage *))completion
{
    [self getDeviceInfo:[_currentUser getUserId] familyID:_currentFamilyID applianceID:applianceID completion:completion];
}

/**
 *  修改家电信息
 */
- (void)deviceModifyInfo:(NSString *)applianceID applianceName:(NSString *)applianceName completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_DEVICE_MODIFY()];
    
    NSString *form = [_formGenerator deviceModifyInfoWithNSString:applianceID withNSString:[_currentUser getSessionId] withNSString:applianceName withNSString:@"" withInt:BaseAPI_get_DEVICE_MODIFY()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

#pragma mark 绑定设备

/**
 *  @brief  判断设备是否已进入配置模式
 */
- (BOOL)isDeviceReady
{
    BOOL flag = [[MDXPGApplianceApi deviceManager] isDeviceReady];
    
//    if (flag && [_currentQRCodeSN length] > 4)
//    {
//        NSString *currentSSID = [[[MDXPGApplianceApi deviceManager] getCurrentSSID] lowercaseString];
//        
//        NSString *suffix = [[_currentQRCodeSN substringFromIndex:_currentQRCodeSN.length-4] lowercaseString];
//        
//        if (![currentSSID hasPrefix:@"net"] || ![currentSSID hasSuffix:suffix])
//        {
//            flag = NO;
//        }
//    }
    
    return flag;
}

- (void)connectDevice:(NSString *)ssid completion:(void (^)(NSDictionary *, NSError *))completion
{
    [[MDXPGApplianceApi deviceManager] connectDevice:ssid success:^(NSDictionary *dic) {
        
        if (completion)
        {
            completion(dic, nil);
        }
        
    } fail:^(NSError *error) {
        
        if (completion)
        {
            completion(nil, error);
        }
    }];
}

/**
 *  @brief  搜索家庭AP列表，10秒超时失败
 */
- (void)findWifiApList:(void (^)(NSArray *, NSError *))completion
{
    [[MDXPGApplianceApi deviceManager] findWifiApList:^(NSArray *array) {
        
        if (completion)
        {
            completion(array, nil);
        }
        
    } fail:^(NSError *error) {
        
        if (completion)
        {
            completion(nil, error);
        }
    }];
}

- (void)bindDevice:(NSString *)homeSSID password:(NSString *)password security:(MDWifiSecurity)security sessionId:(NSString *)sessionId homegroupId:(NSString *)homegroupId qrcodeSN:(NSString *)qrcodeSN deviceName:(NSString *)deviceName completion:(void (^)(NSDictionary *, NSError *))completion
{
    NSLog(@"--->> start bind device... WiFi = %@ password = %@", homeSSID, password);
    [[MDXPGApplianceApi deviceManager] bindDevice:homeSSID
                                         password:password
                                         security:security
                                      accessToken:[_currentUser getAccessToken]
                                        sessionId:[_currentUser getSessionId]
                                      homegroupId:homegroupId
                                         qrcodeSN:qrcodeSN
                                       deviceName:deviceName
                                          success:^(NSDictionary *dic) {
        
        NSLog(@"--->> success: %@", dic);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            completion(dic, nil);
        });
        
    } fail:^(NSError *error) {
        
        NSLog(@"--->> fail: %@", error);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            completion(nil, error);
        });
    }];
}

- (void)bindDevice:(NSString *)homeSSID password:(NSString *)password security:(MDWifiSecurity)security qrcodeSN:(NSString *)qrcodeSN deviceName:(NSString *)deviceName completion:(void (^)(NSDictionary *, NSError *))completion
{
    [self bindDevice:homeSSID password:password security:security sessionId:[_currentUser getSessionId] homegroupId:_currentFamilyID qrcodeSN:qrcodeSN deviceName:deviceName completion:completion];
}


#pragma mark - 更新

/**
 * 获取最新的更新包版本号
 */
- (void)checkForUpdate:(void (^)(BaseMessage *, NSArray *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APP_CHECKFORUPDATE()];
    
    NSString *form = [_formGenerator app_checkforupdateWithInt:BaseAPI_get_APP_CHECKFORUPDATE()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSMutableArray *infoArray = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                MessageInfo *info = [_jsonParser CheckforupdateWithNSString:responseString];
                
                id<JavaUtilList> versionInfoList = [info getBeanInfo];
                
                infoArray = [NSMutableArray new];
                
                for (VersionInfo *info in versionInfoList)
                {
                    [infoArray addObject:info];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, infoArray);
        }
    }];
}

/**
 * 获取升级包信息
 */
- (void)getLastestAppInfo:(NSString *)versionCode completion:(void (^)(BaseMessage *, AppInfo *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APP_UPDATE()];
    
    NSString *form = [_formGenerator app_updateWithNSString:versionCode withInt:BaseAPI_get_APP_UPDATE()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        AppInfo *appInfo = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                MessageInfo *info = [_jsonParser App_updateResponseWithNSString:responseString];
                
                appInfo = (AppInfo *)[info getBeanInfo];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, appInfo);
        }
    }];
}

/**
 * 刷新SessionID
 */
- (void)refreshSession:(NSString *)sessionID completion:(void(^)(BaseMessage *baseMessage))completion
{
    NSString *form = [_formGenerator refreshSessionWithNSString:sessionID withInt:BaseAPI_get_SESSION_REFRESH()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_SESSION_REFRESH()
                                               ];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)refreshSession:(void (^)(BaseMessage *))completion
{
    [self refreshSession:[_currentUser getSessionId] completion:completion];
}


#pragma mark - 电量

/**
 * 查询电量
 */
- (void)queryElec:(NSString *)applianceID type:(int)type year:(int)year month:(int)month day:(int)day completion:(void (^)(BaseMessage *, Elec *))completion
{
    NSString *date = [NSString stringWithFormat:@"%d-%02d-%02d", year, month, day];
    
    self.elecTotalDay = [DateUtil getDayOfMonthWithNSString:date];
    
    date = [NSString stringWithFormat:@"%d-%02d-01", year, month];
    
    NSString *jsonString = [_jsonParser queryElecRequestWithNSString:applianceID withInt:type withNSString:date];
    
    NSString *form = [_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_ELEC_QUERY()];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_ELEC_QUERY() isFunc:isFunc];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        Elec *elec = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser queryElecResponseWithNSString:rawData withInt:(jint)self.elecTotalDay];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                elec = (Elec *)[info getBeanInfo];
                
                if ([baseMessage getCode] == -1)
                {
                    elec = [Elec new];
                    id<JavaUtilList> list = [[JavaUtilArrayList alloc] init];
                    for (int i = 0; i < self.elecTotalDay; i++)
                    {
                        QueryElecCell *elecCell = [[QueryElecCell alloc] init];
                        [elecCell setDateKeyWithInt:i];
                        [elecCell setElecValueWithDouble:0.0];
                        [list addWithId:elecCell];
                    }
                    [elec setCellsWithJavaUtilList:list];
                    [baseMessage setCodeWithInt:0];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, elec);
        }
    }];
}


#pragma mark - 睡眠曲线

/**
 * 获取睡眠曲线状态
 */
- (void)getSleepCurveStatus:(NSString *)applianceID mode:(int)mode completion:(void (^)(BaseMessage *, NSArray *))completion
{
    NSString *jsonString = [_jsonParser getSleepCurveStatusRequestWithNSString:applianceID withInt:mode];
    
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CURVE_QUERY() isFunc:isFunc];
    
    NSString *form = [_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_CURVE_QUERY()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSMutableArray *curves = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser getSleepCurveStatusResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                curves = [NSMutableArray new];
                
                IOSObjectArray *objectArray = (IOSObjectArray *)[info getBeanInfo];
                
                for (id object in objectArray)
                {
                    [curves addObject:object];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, curves);
        }
    }];
}

/**
 * 更新睡眠曲线值
 */
- (void)updateSleepCurve:(NSString *)applianceID curveSleep:(CurveSleep *)curveSleep completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CURVE_UPADTE() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser UpdateSleepCurveRequestWithNSString:applianceID withCurveSleep:curveSleep];
    
    NSString *form = [_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_CURVE_UPADTE()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser UpdateSleepCurveResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

/**
 * 开启睡眠曲线
 */
- (void)startCurveSleep:(NSString *)applianceID curveSleep:(CurveSleep *)curveSleep completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CURVE_START() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser StartSleepCurveRequestWithNSString:applianceID withCurveSleep:curveSleep];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_CURVE_START()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser StartSleepCurveResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

/**
 * 关闭睡眠曲线
 */
- (void)stopCurveSleep:(NSString *)applianceID completion:(void(^)(BaseMessage *baseMessage))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CURVE_STOP() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser CloseSleepCurveRequestWithNSString:applianceID];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_CURVE_STOP()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser CloseSleepCurveResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

#pragma mark - Depracated
/**
 * 添加睡眠曲线
 */
- (void)addCurveSleep:(CurveSleep *)curveSleep completion:(void(^)(BaseMessage *baseMessage))completion
{
    
}

/**
 * 删除睡眠曲线
 */
- (void)deleteCurveSleep:(CurveSleep *)curveSleep completion:(void (^)(BaseMessage *))completion
{
    
}


#pragma mark - 空调体检

/**
 * 开始体检
 */
- (void)startACCheck:(NSString *)applianceID completion:(void (^)(BaseMessage *, CheckDetails *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CHECK_START() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser StartACCheckRequestWithNSString:applianceID];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_CHECK_START()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        CheckDetails *checkDetails = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser StartACCheckResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                checkDetails = (CheckDetails *)[info getBeanInfo];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, checkDetails);
        }
    }];
}

/**
 * 获取体检信息
 */
- (void)getACCheckDetails:(NSString *)applianceID completion:(void (^)(BaseMessage *, NSArray *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_CHECK_DETAIL() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser AcCheckDetailsRequestWithNSString:applianceID];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_CHECK_DETAIL()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSMutableArray *itemDetailsArray = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser AcCheckDetailsResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                itemDetailsArray = [NSMutableArray new];
                
                IOSObjectArray *tempArray = (IOSObjectArray *)[info getBeanInfo];
                
                for (int i = 0; i < [tempArray length]; i++)
                {
                    [itemDetailsArray addObject:IOSObjectArray_Get(tempArray, i)];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, itemDetailsArray);
        }
    }];
}


#pragma mark - 预约

/**
 * 添加预约
 */
- (void)addDeviceAppoint:(DeviceAppoint *)appoint completion:(void (^)(BaseMessage *, NSString *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APPOINT_ADD() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser addApplianceAppointRequestWithDeviceAppoint:appoint withIDateZoomTransformer:[MDDateTansformer new]];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_APPOINT_ADD()];
    
    NSDictionary *parameters = [self JSONObjectFromForm:form];
    [parameters setValue:@"" forKey:@"time"];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSString *appointID = @"";
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser addApplianceAppointResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                appointID = (NSString *)[info getBeanInfo];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, appointID);
        }
    }];
}

/**
 * 修改预约
 */
- (void)updateDeviceAppoint:(DeviceAppoint *)appoint completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APPOINT_UPDATE() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser updateApplianceAppointRequestWithDeviceAppoint:appoint withIDateZoomTransformer:[MDDateTansformer new]];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_APPOINT_UPDATE()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser updateApplianceAppointResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

/**
 * 获取预约列表
 */
- (void)getAppointList:(NSString *)applianceID completion:(void (^)(BaseMessage *, NSArray *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APPOINT_QUERY() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser getApplianceAppointDetailRequestWithNSString:applianceID];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_APPOINT_QUERY()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSMutableArray *appointArray = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                appointArray = [NSMutableArray new];
                
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser getApplianceAppointDetailResponseWithNSString:rawData withIDateZoomTransformer:[MDDateTansformer new]];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                id<JavaUtilList> list = [info getBeanInfo];
                
                for (id object in list)
                {
                    [appointArray addObject:object];
                }
            }
        }
        
        if (completion)
        {
            completion(baseMessage, appointArray);
        }
    }];
}

/**
 * 开启预约
 */
- (void)startAppoint:(NSString *)appointID completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APPOINT_START() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser startApplianceAppointRequestWithNSString:appointID];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_APPOINT_START()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser startApplianceAppointResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

/**
 * 关闭预约
 */
- (void)stopAppoint:(NSString *)appointID completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_APPOINT_STOP() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser closeApplianceAppointRequestWithNSString:appointID];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_APPOINT_STOP()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser closeApplianceAppointResponseWithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}


#pragma mark - T1

- (void)queryT1Temperature:(NSString *)applianceID completion:(void (^)(BaseMessage *, BOOL))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_T1_QUERY() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser queryT1ScheduleWithLong:[applianceID longLongValue]];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_T1_QUERY()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        BOOL onoff = NO;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
                MessageInfo *info = [_jsonParser queryT1WithNSString:rawData];
                
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                onoff = [[info getBeanInfo] booleanValue];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, onoff);
        }
    }];
}

- (void)addT1Temperature:(NSString *)applianceID time:(NSString *)time week:(NSString *)week repeat:(int)repeat completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_T1_ADD() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser addT1ScheduleWithNSString:applianceID withNSString:time withNSString:week withInt:repeat withIDateZoomTransformer:[MDDateTansformer new]];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_T1_ADD()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
//                NSString *rawData = [_jsonParser decodeReturnDataWithNSString:responseString withSecurityHandle:[MDSecurityHandler sharedInstance] withNSString:[_currentUser getAccessToken]];
                
//                MessageInfo *info = [_jsonParser closeApplianceAppointResponseWithNSString:rawData];
//                
//                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
//                [baseMessage setMessageWithNSString:[info getMsg]];
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)updateT1Temperature:(NSString *)applianceID time:(NSString *)time week:(NSString *)week repeat:(int)repeat completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_T1_UPDATE() isFunc:isFunc];
    
    NSString *jsonString = [_jsonParser addT1ScheduleWithNSString:applianceID withNSString:time withNSString:week withInt:repeat withIDateZoomTransformer:[MDDateTansformer new]];
    
    NSString *form =[_formGenerator app2baseTranmitWithNSString:[_currentUser getSessionId] withNSString:[_currentUser getAccessToken] withNSString:jsonString withInt:BaseAPI_get_T1_UPDATE()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                
            }
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)userIcon:(UIImage *)image completion:(void (^)(BaseMessage *, NSString *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_USER_PIC()];
    
    id<JavaUtilMap> map = [_formGenerator user_iconWithNSString:[_currentUser getSessionId] withInt:BaseAPI_get_USER_PIC()];
    
    NSMutableDictionary *params = [NSMutableDictionary new];
    
    for (id<JavaUtilMap_Entry> set in [map entrySet])
    {
        NSString *key = [set getKey];
        NSString *value = [set getValue];
        
        [params setObject:value forKey:key];
    }
    
    [_netUtil upload:urlString parameters:params image:image completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSString *urlString = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                MessageInfo *info = [_jsonParser getProfileURLWithNSString:responseString];
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                urlString = (NSString *)[info getBeanInfo];
            }
        }
        
        if (completion)
        {
            completion(baseMessage, urlString);
        }
    }];
}

- (void)queryDeviceInfo:(ApplianceInfo *)info completion:(void (^)(BaseMessage *, DeviceStatus *, AirConditionerFuncs *))completion
{
    AirConditionerFuncs *funcs = [[AirConditionerFuncs alloc] init];
    
    IOSByteArray *order = [[FactoryDataBody createQueryRequest] toBytes];
    
    [self transparentCmd:[info getApplianceId] order:order completion:^(BaseMessage *baseMessage, NSString *reply, DeviceStatus *status) {
        
        DeviceStatus *defaultStatus = [DeviceStatus new];
        defaultStatus->setTemperature_ = 26;
        defaultStatus->mode_ = IDataBodyDevStauts_get_MODE_COLD();
        defaultStatus->fanSpeed_ = IDataBodyDevStauts_get_WIND_SPEED_AUTO();
        defaultStatus->powerStatus_ = IDataBody_get_ON();
        self.status = defaultStatus;
        
        if ([baseMessage getCode] == 0)
        {
            if (![info getApplianceId] || [[info getApplianceId] equalsIgnoreCase:@""])
            {
                // 无SN机器，基础功能
                [funcs setBaseFunc];
                [_sharePerferenceHandler updateWithNSString:[info getApplianceId] withNSString:[funcs description]];
                completion(baseMessage, status, funcs);
            }
            else if ([[_sharePerferenceHandler getWithNSString:[info getApplianceId]] isEqualToString:@""])
            {
                if (status->protocol_ == 0x00)
                {
                    // 0协议设备，基础功能
                    
                    [baseMessage setCodeWithInt:-99];
                    [baseMessage setMessageWithNSString:@"Failed to recognize"];
                    
                    completion(baseMessage, status, funcs);
                    return;
                }
                
                if ([AirConditionerFuncSN hasTargetSNWithNSString:[info getApplianceSN]])
                {
                    AirConditionerFuncs *funcs = [self getFuncsViaSN:[info getApplianceSN]];
                    completion(baseMessage, status, funcs);
                    return;
                }
                else
                {
                    // B5 请求
                    [self queryB5:[info getApplianceId] completion:^(BaseMessage *base, AirConditionerFuncs *funcs) {
                        
                        if ([base getCode] == 0)
                        {
                            // 解析成Func类
                            // 保存一下
                            B5Timeout = NO;
                            
                            [_sharePerferenceHandler updateWithNSString:[info getApplianceId] withNSString:[funcs description]];
                            
                            completion(base, status, funcs);
                        }
                        else
                        {
                            // 超时，返回全功能
                            B5Timeout = YES;
                            [base setCodeWithInt:-99];
                            [base setMessageWithNSString:@"Failed to recognize"];
                            completion(base, status, funcs);
                        }
                    }];
                }
            }
            else
            {
                // 直接拿出来
                AirConditionerFuncs *fun = [[AirConditionerFuncs alloc] initWithNSString:[_sharePerferenceHandler getWithNSString:[info getApplianceId]]];
                completion(baseMessage, status, fun);
            }
        }
        else
        {
            if ([AirConditionerFuncSN hasTargetSNWithNSString:[info getApplianceSN]])
            {
                AirConditionerFuncs *funcs = [self getFuncsViaSN:[info getApplianceSN]];
                completion(baseMessage, status, funcs);
                return;
            }
            
            if ([[_sharePerferenceHandler getWithNSString:[info getApplianceId]] isEqualToString:@""])
            {
                // B5 请求
                [self queryB5:[info getApplianceId] completion:^(BaseMessage *base, AirConditionerFuncs *funcs) {
                    
                    if ([base getCode] == 0)
                    {
                        //解析成Func类
                        //保存一下
                        status->protocol_ = 0x03;
                        B5Timeout = NO;
                        [_sharePerferenceHandler updateWithNSString:[info getApplianceId] withNSString:[funcs description]];
                        
                        completion(base, status, funcs);
                    }
                    else
                    {
                        // 超时，返回全功能
                        B5Timeout = YES;
                        status->protocol_ = 0x00;
                        [base setCodeWithInt:-99];
                        [base setMessageWithNSString:@"Failed to recognize"];
                        completion(base, status, funcs);
                    }
                }];
            }
            else
            {
                // 直接拿出来
                AirConditionerFuncs *fun = [[AirConditionerFuncs alloc] initWithNSString:[_sharePerferenceHandler getWithNSString:[info getApplianceId]]];
                completion(baseMessage, status, fun);
            }
        }
    }];
}

- (void)queryB5:(NSString *)applianceId completion:(void (^)(BaseMessage *, AirConditionerFuncs *))completion
{
    IOSByteArray *order = [[FactoryDataBody createQueryB5Request] toBytes];
    
    [self transparentCmd:applianceId order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
        
        BaseMessage *baseMessage = nil;
        AirConditionerFuncs *mfunc = [AirConditionerFuncs new];
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
            
            [mfunc everythingEnable];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
            
            if ([baseMessage getCode] != 0 || [[info getErrCode] integerValue] != 0)
            {
                [baseMessage setCodeWithInt:-99];
                [baseMessage setMessageWithNSString:@"Failed to recognize"];
                
                [baseMessage setCodeWithInt:(jint)[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
                
                [mfunc everythingEnable];
            }
            else
            {
                @try
                {
                    NSString *reply = (NSString *)[info getBeanInfo];
                    
                    IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
                    
                    IOSByteArray *byteArray2 = replyToTotalByteArray(reply, [_currentUser getAccessToken]);
                    jbyte protocol = [byteArray2 byteAtIndex:8];
                    
                    if (protocol != 0)
                    {
                        mfunc->updownFan_ = YES;
                    }
                    else
                    {
                        mfunc->updownFan_ = NO;
                    }
                    
                    mfunc->nestCheck_ = YES;
                    mfunc->unitChangeable_ = YES;
                    
                    if ([byteArray byteAtIndex:0] == -75)
                    {
                        //int type = [byteArray byteAtIndex:1];    // 总功能数
                        
                        for (int i = 4; i < [byteArray length]; )
                        {
                            jbyte d2 = [byteArray byteAtIndex:i-2];
                            jbyte d1 = [byteArray byteAtIndex:i-1];
                            int length = [byteArray byteAtIndex:i];   // 长度
                            IOSByteArray *data = [IOSByteArray arrayWithLength:length];
                            *[data byteRefAtIndex:0] = (jbyte)[byteArray byteAtIndex:i+1];
                            
                            setFuncEnable(d1, d2, data, mfunc);
                            
                            i = i + length + 3;
                        }
                    }
                }
                @catch (NSException *exception)
                {
                    NSLog(@"%@", exception);
                    
                    [baseMessage setCodeWithInt:-99];
                    [baseMessage setMessageWithNSString:@"Failed to recognize"];
                    mfunc = [AirConditionerFuncs new];
                    [mfunc everythingEnable];
                }
            }
        }
        completion(baseMessage, mfunc);
    }];
}

- (void)queryFansRuntime:(NSString *)applianceId completion:(void (^)(BaseMessage *, int))completion
{
    IOSByteArray *order = [[FactoryDataBody createQueryTimeRequest] toBytes];
    
    [self transparentCmd:applianceId order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
        
        BaseMessage *baseMessage = nil;
        NSString *reply = nil;
        int time;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            if ([baseMessage getCode] == 0)
            {
                MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
                
                reply = (NSString *)[info getBeanInfo];
                
                IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
                
                time = [byteArray byteAtIndex:6] + [byteArray byteAtIndex:7] * 16;
            }
        }
        
        completion(baseMessage, time);
    }];
}

- (void)clearPowerCal:(NSString *)applianceId completion:(void (^)(BaseMessage *))completion
{
    IOSByteArray *order = [[FactoryDataBody createQueryPowerRequestWithBoolean:NO] toBytes];
    
    [self transparentCmd:applianceId order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
        
        BaseMessage *baseMessage = nil;
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
            
            @try
            {
                MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
                [baseMessage setCodeWithInt:[[info getErrCode] intValue]];
                [baseMessage setMessageWithNSString:[info getMsg]];
            }
            @catch (NSException *exception)
            {
                NSLog(@"%@", exception);
                [baseMessage setCodeWithInt:-1];
                [baseMessage setMessageWithNSString:@"超时"];
            }
        }
        
        completion(baseMessage);
    }];
}

- (AirConditionerFuncs *)setFunctions:(ApplianceInfo *)info type:(jint)type
{
    NSString *s = [_sharePerferenceHandler getWithNSString:[info getApplianceId]];
    
    AirConditionerFuncs *funcs;
    
    if ([s isEqualToString:@""])
    {
        funcs = [AirConditionerFuncs new];
    }
    else
    {
        funcs = [[AirConditionerFuncs alloc] initWithNSString:s];
        
//        if ([FactoryDataBody getProtocol] == 0x00)
//        {
//            funcs->selfcheck_ = NO;
//        }
    }
    
    funcs->nestCheck_ = YES; // 滤网默认有
    funcs->hotcold_ = type;
    funcs->unitChangeable_ = YES;
    
    if ([FactoryDataBody getProtocol] == 0x00)
    {
        [funcs setBaseFunc];
    }
    
    if ([FactoryDataBody getProtocol] == (jbyte)0x03)
    {
        if (B5Timeout)
        {
            funcs->powerCal_ = NO;
        }
    }
    
    if (type == AirConditionerFuncs_get_COLD_AC())
    {
        // 单冷机
        [funcs toOnlyCool];
        
        if ([FactoryDataBody getProtocol] == (jbyte)0x00)
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = NO;
        }
        else
        {
            // B5 超时默认
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = YES;
        }
    }
    else if (type == AirConditionerFuncs_get_COLDHOT_AC())
    {
        // 多功能机
        [funcs toAllEnable];
        
        if ([FactoryDataBody getProtocol] == (jbyte)0x00)
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = NO;
        }
        else
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = YES;
        }
    }
    else if (type == AirConditionerFuncs_get_HOT_AC())
    {
        [funcs toOnlyHot];
        
        if ([FactoryDataBody getProtocol] == (jbyte)0x00)
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = NO;
        }
        else
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = YES;
        }
    }
    else if (type == AirConditionerFuncs_get_COLD_AC_SUB())
    {
        [funcs toSubCool];
        
        if ([FactoryDataBody getProtocol] == (jbyte)0x03)
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = YES;
            funcs->strongHot_ = NO;
        }
        else if ([FactoryDataBody getProtocol] == (jbyte)0x00)
        {
            funcs->leftrightFan_ = NO;
            funcs->updownFan_ = NO;
        }
    }
    else
    {
        [funcs toAllEnable];
    }
    
    [_sharePerferenceHandler updateWithNSString:[info getApplianceId] withNSString:[funcs description]];
    
    AirConditionerFuncs *currFunc = [[AirConditionerFuncs alloc] initWithNSString:[_sharePerferenceHandler getWithNSString:[info getApplianceId]]];
    currFunc->hotcold_ = type;
    
    return currFunc;
}

- (void)clearFunctionsRecord:(ApplianceInfo *)info
{
    [_sharePerferenceHandler delete__WithNSString:[info getApplianceId]];
}

- (AirConditionerFuncs *)getFunctions:(ApplianceInfo *)info
{
    return [[AirConditionerFuncs alloc] initWithNSString:[_sharePerferenceHandler getWithNSString:[info getApplianceId]]];
}

- (AirConditionerFuncs *)getFuncsViaSN:(NSString *)sn
{
    AirConditionerFuncSN *funcSN = [[AirConditionerFuncSN alloc] initWithNSString:sn];
    return [funcSN getFuncs];
}

- (void)sendActivateEmail:(NSString *)email completion:(void (^)(BaseMessage *))completion
{
    NSString *urlString = [self getTargetURLAppendParams:BaseAPI_get_SENDACTIVEMAIL()];
    
    NSString *form =[_formGenerator sendActiveEmailWithNSString:email withInt:BaseAPI_get_SENDACTIVEMAIL()];
    
    [_netUtil post:urlString parameters:[self JSONObjectFromForm:form] completion:^(NSString *responseString, NSError *error) {
        
        BaseMessage *baseMessage = nil;
        NSString *msg = @"";
        
        if (error)
        {
            baseMessage = [[BaseMessage alloc] init];
            [baseMessage setCodeWithInt:(jint)[error code]];
            [baseMessage setMessageWithNSString:[error localizedDescription]];
        }
        else
        {
            baseMessage = [BaseMessage new];
            
            @try
            {
                OrgJsonJSONObject *jsonObj = [[OrgJsonJSONObject alloc] initWithNSString:responseString];
                [baseMessage setCodeWithInt:(jint)[[jsonObj getStringWithNSString:@"errorCode"] integerValue]];
                
                @try
                {
                    msg = [jsonObj getStringWithNSString:@"msg"];
                }
                @catch (NSException *exception)
                {
                    NSLog(@"%@", exception);
                }
            }
            @catch (NSException *exception)
            {
                [baseMessage setCodeWithInt:-1];
                [baseMessage setMessageWithNSString:@"unknown error"];
                NSLog(@"%@", exception);
            }
            
            [baseMessage setMessageWithNSString:msg];
        }
        
        if (completion)
        {
            completion(baseMessage);
        }
    }];
}

- (void)queryB5ForDehumi:(NSString *)applianceId completion:(void (^)(BaseMessage *, DeHumiFunctions *))completion
{
    if ([[_sharePerferenceHandler getWithNSString:applianceId] isEqualToString:@""])
    {
        IOSByteArray *order = [[FactoryDataBody createQueryB5RequestWithByte:(jbyte)0xA1] toBytes];
        
        [self transparentCmd:applianceId order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
            
            BaseMessage *baseMessage = nil;
            DeHumiFunctions *funcs = [DeHumiFunctions new];
            
            if (error)
            {
                baseMessage = [[BaseMessage alloc] init];
                [baseMessage setCodeWithInt:(jint)[error code]];
                [baseMessage setMessageWithNSString:[error localizedDescription]];
            }
            else
            {
                baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
                
                if ([baseMessage getCode] == 0)
                {
                    MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
                    
                    NSString *reply = [info getBeanInfo];
                    
                    IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
                    
                    if ([byteArray byteAtIndex:0] == -75)
                    {
                        //int type = [byteArray byteAtIndex:1];    // 总功能数
                        
                        for (int i = 4; i < [byteArray length]; )
                        {
                            jbyte d2 = [byteArray byteAtIndex:i-2];
                            jbyte d1 = [byteArray byteAtIndex:i-1];
                            int length = [byteArray byteAtIndex:i];   // 长度
                            IOSByteArray *data = [IOSByteArray arrayWithLength:length];
                            *[data byteRefAtIndex:0] = [byteArray byteAtIndex:i+1];
                            setFuncEnable(d1, d2, data, funcs);
                            i = i + length + 3;
                        }
                    }
                }
                else
                {
                    
                }
            }
            
            [_sharePerferenceHandler updateWithNSString:applianceId withNSString:[funcs description]];
            
            NSLog(@"除湿B5: %@", [funcs description]);
            
            completion(baseMessage, funcs);
        }];
    }
    else
    {
        BaseMessage *base = [BaseMessage new];
        [base setCodeWithInt:0];
        
        DeHumiFunctions *funcs = (DeHumiFunctions *)[self objectFromJSON:[_sharePerferenceHandler getWithNSString:applianceId] aClass:[DeHumiFunctions class]];
        
        NSLog(@"除湿B5: %@", [funcs description]);
        
        completion(base, funcs);
    }
}

- (void)queryB5ForHumi:(NSString *)applianceId completion:(void (^)(BaseMessage *, HumiFunctions *))completion
{
    if ([[_sharePerferenceHandler getWithNSString:applianceId] isEqualToString:@""])
    {
        IOSByteArray *order = [[FactoryDataBody createQueryB5RequestWithByte:(jbyte)0xFD] toBytes];
        
        [self transparentCmd:applianceId order:order completionWithoutHandling:^(NSError *error, NSString *responseString) {
            
            BaseMessage *baseMessage = nil;
            HumiFunctions *funcs = [HumiFunctions new];
            
            if (error)
            {
                baseMessage = [[BaseMessage alloc] init];
                [baseMessage setCodeWithInt:(jint)[error code]];
                [baseMessage setMessageWithNSString:[error localizedDescription]];
            }
            else
            {
                baseMessage = [_jsonParser IsSuccessWithNSString:responseString];
                
                if ([baseMessage getCode] == 0)
                {
                    MessageInfo *info = [_jsonParser applianceSendResponseWithNSString:responseString];
                    
                    NSString *reply = [info getBeanInfo];
                    
                    IOSByteArray *byteArray = replyToByteArray(reply, [_currentUser getAccessToken]);
                    
                    if ([byteArray byteAtIndex:0] == -75)
                    {
                        //int type = [byteArray byteAtIndex:1];    // 总功能数
                        
                        for (int i = 4; i < [byteArray length]; )
                        {
                            jbyte d2 = [byteArray byteAtIndex:i-2];
                            jbyte d1 = [byteArray byteAtIndex:i-1];
                            int length = [byteArray byteAtIndex:i];   // 长度
                            IOSByteArray *data = [IOSByteArray arrayWithLength:length];
                            *[data byteRefAtIndex:0] = [byteArray byteAtIndex:i+1];
                            setFuncEnable(d1, d2, data, funcs);
                            i = i + length + 3;
                        }
                    }
                }
                else
                {
                    
                }
            }
            
            [_sharePerferenceHandler updateWithNSString:applianceId withNSString:[funcs description]];
            
            NSLog(@"加湿B5: %@", [funcs description]);
            
            completion(baseMessage, funcs);
        }];
    }
    else
    {
        BaseMessage *base = [BaseMessage new];
        [base setCodeWithInt:0];
        
        HumiFunctions *funcs = (HumiFunctions *)[self objectFromJSON:[_sharePerferenceHandler getWithNSString:applianceId] aClass:[HumiFunctions class]];
        
        NSLog(@"加湿B5: %@", [funcs description]);
        
        completion(base, funcs);
    }
}

- (id)objectFromJSON:(NSString *)jsonString aClass:(Class)aClass
{
    id anObejct = [[aClass alloc] init];
    
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
    
    for (NSString *key in [dic allKeys])
    {
        NSString *newKey = [key stringByAppendingString:@"_"];
        [anObejct setValue:dic[key] forKeyPath:newKey];
    }
    
    return anObejct;
}

@end
